import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;

import suit.ui.Application;
import suit.ui.Box;
import suit.ui.Button;
import suit.ui.Entry;
import suit.ui.Label;
import suit.ui.Screen;
import suit.ui.themes.DefaultTheme;

public class Metronome extends Application implements Button.Clicked {

	private Screen main;
	private Box vbox;
	private Label title;
	private Label t;
	private Entry tempo;
	private Box hbox;
	private Button stop;
	private Button start;
	private Label status;

	private Timer metronome;

	public Metronome() {
		main = new Screen(new DefaultTheme());
		vbox = new Box(Box.Vert, true, 10);
		vbox.setBorderWidth(10);

		title = new Label("Metronome");
		vbox.pack(title, true, true, 0);

		t = new Label("Tempo (bpm):");
		t.setAlign(Label.BOTTOM | Label.LEFT);
		vbox.pack(t, true, true, 0);
		tempo = new Entry("120");
		vbox.pack(tempo, true, true, 0);

		hbox = new Box(Box.Horiz, true, 10);

		stop = new Button("Stop");
		stop.connect(this);
		hbox.pack(stop, true, true, 0);
		start = new Button("Start");
		start.connect(this);
		hbox.pack(start, true, true, 0);

		vbox.pack(hbox, true, true, 0);

		status = new Label("Stopped");
		vbox.pack(status, true, true, 0);

		main.add(vbox);
		setScreen(main);

	}

	public void onClicked(Button source) {
		if (source == start) {
			int tempoint;
			try {
				tempoint = Integer.parseInt(tempo.getText());
				startMetronome(tempoint);
			} catch (NumberFormatException e) {
				status.setText("Tempo is not a number!");
			}
		} else if (source == stop) {
			stopMetronome();
		}
	}

	public void startMetronome(int tempo) {
		try {
			metronome.cancel();
		} catch (Exception e) {
		}
		metronome = new Timer();
		int delay = 1000 * 60 / tempo;
		metronome.scheduleAtFixedRate(new PlayBeat(), 0, delay);
		String name;
		if (tempo >= 200)
			name = "Prestissimo";
		else if (tempo >= 168)
			name = "Presto";
		else if (tempo >= 120)
			name = "Allegro";
		else if (tempo >= 112)
			name = "Allegro Moderato";
		else if (tempo >= 108)
			name = "Moderato";
		else if (tempo >= 76)
			name = "Andante";
		else if (tempo >= 72)
			name = "Adagietto";
		else if (tempo >= 66)
			name = "Adagio";
		else if (tempo >= 60)
			name = "Larghetto";
		else if (tempo >= 40)
			name = "Largo";
		else
			name = "Pretty slow!";
		status.setText(name + " (" + tempo + " bpm)");
	}

	public void stopMetronome() {
		metronome.cancel();
		status.setText("Stopped");
	}

	public boolean onKeyReleased(int key) {
		if (key == -8)
			notifyDestroyed();
		return false;
	}

	private class PlayBeat extends TimerTask {
		public final void run() {
			try {
				Manager.playTone(93, 100, 100);
			} catch (MediaException e) {
				status.setText(e.getMessage());
			}
		}
	}

}
